<?php

namespace app\api\controller;

use app\common\controller\Common;
use com\YHprobe;
use think\Db;
use think\Request;


class Index  extends Common
{

    public function index()
    {
        return returnJson(['data' => []]);
    }

    public function logout()
    {
        $param = session('authkey');
        //var_dump($param);exit;
        cache('Auth_' . $param, null);
        session('authkey', null);
        $this->success('安全退出', url('login/index'), null, 0);
    }


    /**
     * 系统状态详细信息，登陆后调用
     */
    public function systemDetail()
    {
        try {
            //获取系统状态信息
            $res = YHprobe::sys_linux();
            //硬盘剩余容量
            $df = round(@disk_free_space(".") / (1024 * 1024 * 1024), 3);
            //硬盘总容量，web服务器目录所在磁盘的空间，最好服务器只有一个硬盘
            $dt = round(@disk_total_space(".") / (1024 * 1024 * 1024), 3);
            //读取数据库中录音文件的总数
            $totle = Db::name("meeting_live_speech")->where(['is_delete' => 0])->count();
            //账号总数
            $account_count = Db::name("admin_user")->count();
            //未禁用账号个数
            $cli_count = Db::name("admin_user")->where(['status' => 1])->count();
            //获取cpu状态
            $cpu = YHprobe::cpu_lix();
            //设备状态
            $equ_status['1'] = Db::name("equipment")->where(['connection' => 1, 'status' => 1])->where('type','in','1,4')->count();
            $equ_status['2'] = Db::name("equipment")->where(['connection' => 2, 'status' => 1])->where('type','in','1,4')->count();
            $equipment = Db::name("equipment")->where(['connection' => 1, 'status' => 1])->field('equipmentid,title')->select();

            $data = [
                'cpu_num' => $res['cpu']['num'],    //cpu核，24核，$res['cpu']['num']
                'cpu_model' => $res['cpu']['model'],    //cpu详情  $res['cpu']['model']
                'disk_free' => $dt - $df,
                'disk_totle' => $dt,
                'memory_totol' => $res["memTotal"],     //cpu物理内存总量  $res["memTotal"]
                'memory_free' => $res["memRealUsed"],   //cpu空闲内存  $res["memFree"]
                'memory_percent' => $res["memRealPercent"] . "%", //cpu内存 使用率  $res["memPercent"]
                'cpu_percent' => $cpu['percent'] . '%',  //cpu使用率
                'cpu_total_time' => $cpu['total'], //cpu总时间
                'cpu_busy_time' => $cpu['time'], //cpu繁忙时间
                'loadAvg' => $res["loadAvg"],   //cpu负载  $res["loadAvg"]
                'file_totle' => $totle,  //文件总数
                'account_count' => $account_count, //账号总数
                'cli_count' => $cli_count,  //未禁用用户总数量
                'equ_status' => $equ_status,
                'equipment' => $equipment
            ];

            return resultArray(['data' => $data]);
        } catch (\Exception $e) {
            //return resultArray(['errer' => $e->getMessage()]);
            return resultArray(['errer' => '请求失败']);
        }
    }

    public function createAudio()
    {
        if (input('param.did')) {
            return $this->boxCreateOffAudio();
        }
        return $this->audioUpload();
    }


    /**
     * 盒子上传非实时文件
     */
    public function boxCreateOffAudio()
    {
        try {
            $res_param = input('param.');
            if (!$res_param['id']) {
                return resultArray(['error' => '未添加用户id']);
            }
            $extension = $res_param['extension'] ?: pathinfo($res_param['filename'])['extension'];
            $model = Model('LiveSpeech1');
            if ($res_param['fileid']) {
                $model = $model->get($res_param['fileid']);
                //更新列表
                $param = [
                    'formatname' => $res_param['identifier'],
                    'update_time' => time(),
                    'transition_state' => 6,
                    'sid' => $res_param['scene'] ?: 1,
                    'title' => $res_param['title'] ?: '',
                ];
                $model->save($param);
                $result_id = $model->id;
            } else {
                $param = [
                    'uid' => $res_param['id'],
                    'did' => $res_param['did'],
                    'filename' => $res_param['filename'],
                    'formatname' => $res_param['identifier'],
                    'size' => 0,
                    'create_time' => time(), 'update_time' => time(),
                    'is_manual' => $res_param['manual'] ?: 2,
                    'transition_state' => 6,
                    'meeting_tag' => "box" . $res_param['id'] . '-0-' .  $res_param['identifier'],
                    'transfer' => '',
                    'editor' => '',
                    'sid' => $res_param['scene'] ?: 1,
                    'title' => $res_param['title'] ?: '',
                ];
                $result_id = $model->createFileData($param);
            }

            if (!$result_id) {
                return resultArray(['error' => $model->getError()]);
            }
            //插入另一个表
            $params = [
                'meeting_id' => $result_id,
                'device_id' => $model->did,
                'filename' => $res_param['filename'],
                'user_id' => $model->uid,
                'formatname' => $res_param['formatName'] ?: $res_param['identifier'] . "." . $extension,
                'create_time' => time(),
                'update_time' => time()
            ];
            $result = Model('Speech')->data($params)->allowField(true)->save();
            return resultArray(['data' => ['fileId' => $result_id]]);
        } catch (\Exception $e) {
            //return resultArray(['error' => $e->getMessage()]);
            return resultArray(['error' => '请求失败']);
        }
    }

    /**
     * 上传音频
     */
    public function audioUpload()
    {
        try {
            $res_param = input('param.');
            if (!$res_param['id']) {
                return resultArray(['error' => '未添加用户id']);
            }
            $file_path = config('huisheng.upload_audio_dir') . DS . $res_param['identifier'] . DS . $res_param['formatName'];
            if (is_file($file_path)) {
                $param = [
                    'uid' => $res_param['id'],
                    'did' => $res_param['did'] ?: 0,
                    'filename' => $res_param['filename'],
                    'formatname' => $res_param['identifier'],
                    'size' => filesize($file_path),
                    'create_time' => time(), 'update_time' => time(),
                    'is_manual' => $res_param['manual'] ?: 2,
                    'transition_state' => 0,
                    'meeting_tag' => "user" . $res_param['id'] . '-0-' .  $res_param['identifier'],
                    'transfer' => '',
                    'editor' => '',
                    'sid' => $res_param['scene'] ?: 1,
                ];
                $model = Model('LiveSpeech1');
                $result_id = $model->createFileData($param);
                if (!$result_id) {
                    //unlink($dir . DS . $filename);
                    return resultArray(['error' => $model->getError()]);
                }
                //插入另一个表
                $params = [
                    'meeting_id' => $result_id,
                    'device_id' => $res_param['did'] ?: 0,
                    'filename' => $res_param['filename'],
                    'user_id' => $res_param['id'],
                    'formatname' => $res_param['identifier'] . ".wav",
                    'create_time' => time(),
                    'update_time' => time()
                ];
                $result = Model('Speech')->data($params)->allowField(true)->save();
                return resultArray(['data' => ['fileId' => $result_id]]);
            }
            return resultArray(['error' => "未找到文件请重新上传"]);
        } catch (\Exception $e) {
            //return resultArray(['error' => $e->getMessage()]);
            return resultArray(['error' => '请求失败']);
        }
    }

    public function burstUpload()
    {
        try {
            $param = input('param.');

            $destination = config('huisheng.upload_audio_dir') . DS . $param['identifier'];
            if (!is_dir($destination)) {
                @mkdir($destination, 0777, true);
            }
            $result = [
                'message' => "",
                'result' => true,
                'timestamp' => time(),
                'isMerged' => false,
            ];
            //记录文件,判断是否为同一个文件
            $file = $param['identifier'] . "." . pathinfo($param['filename'])['extension'];
            if (Request::instance()->isGet()) {
                $result['uploaded'] = $this->listFilesInUploaded($destination, $file);
                foreach ($result['uploaded'] as $file) {
                    $result['list'][] = [
                        'number' => $file
                    ];
                }
                return json($result, 200);
            }
            if (Request::instance()->isPost()) {
                if (move_uploaded_file($_FILES['file']['tmp_name'], $destination . DS . $file . '.tmp' . $_POST['chunkNumber'])) {
                    $s = $this->listFilesInUploaded($destination, $file);
                    if (count($s) == $_POST['totalChunks']) {
                        cache($file, null);
                        $fp = fopen($destination . DS . $file, 'w');
                        for ($i = 1; $i <= $_POST['totalChunks']; $i++) {
                            if (file_exists($destination . DS . $file . '.tmp' . $i)) {
                                fwrite($fp, file_get_contents($destination . DS . $file . '.tmp' . $i));
                                @unlink($destination . DS . $file . '.tmp' . $i);
                            } else {
                                throw new \Exception('file is loss');
                            }
                        }
                        fclose($fp);
                        file_put_contents($destination . DS . pathinfo($file)['filename'] . '.md5', md5_file($destination . DS . $file));
                        $result['message'] = "uploaded success";
                        $result['fileName'] = $file;
                        $result['isMerged'] = true;
                    }
                    $result['tempName'] = $file . '.tmp' . $_POST['chunkNumber'];
                    $result['uploaded'] = $s;
                    return json($result, 200);
                } else {
                    $result['message'] = "number-" . $_POST['chunkNumber'] . "file uploads failed";
                    $result['result'] = false;
                    return json($result, 400);
                }
            }
        } catch (\Exception $e) {
            $result['message'] = "error:" . $e->getMessage();
            $result['result'] = false;
            return json($result, 400);
        }
    }

    public function transferTragger($id, $num=1)
    {
        if (!$id) {
            return resultArray(['error' => 'id为空']);
        }
        $file = Model('LiveSpeech1')->get($id);
        if (!$file) {
            return resultArray(['error' => '未找到数据']);
        }
        if ($file->transition_state == 1 || $file->transition_state == 2) {
            return resultArray(['data' => '']);
        }
        $formatname = $file->formatname;
        $uid = $file->uid;
        $dir = config('huisheng.upload_audio_dir') . DS . $formatname;
        $ext = pathinfo($file->oneSpeech->filename)['extension'];
        $filename = "$formatname.$ext";
        $push_array = [
            'type' => 1,
            'id' => $id,
            'num' => $num,
            'ori_path' => $dir . DS . $filename,
            'des_path' => config('huisheng.box_audio_dir') . DS . $formatname . ".wav",
        ];
        self::$redis->pushUploadFileQueue($push_array);
        $file->transition_state = 1;
        $file->update_time = time();
        $file->save();
        return resultArray(['data' => '']);
    }

    private function listFilesInUploaded($from, $name)
    {
        $files = array();
        if (!is_dir($from)) {
            return $files;
        }
        $dirs = array($from);
        while (NULL !== ($dir = array_pop($dirs))) {
            if ($dh = opendir($dir)) {
                while (false !== ($file = readdir($dh))) {
                    if ($file == '.' || $file == '..')
                        continue;
                    $path = $dir . '/' . $file;
                    if (is_file($path)) {
                        if (strpos($file, $name . ".tmp") !== false) {
                            $files[] = intval(str_replace($name . ".tmp", "", $file));
                        }
                    }
                }
                closedir($dh);
            }
        }
        return $files;
    }

    public function getServerConfig()
    {
        $config = config('server');
        $scene = Db::name('scenes')->where('status', 1)->field('id,scene,name')->select();
        $config['SCENES'] = $scene;
        return resultArray(['data' => $config]);
    }

    //下载最新版本录音笔
    public function downloadPenApp()
    {
        if (config('huisheng.CAN_DOWNLOAD_PEN_APP')) {
            $model = Model('Version');
            $pen = $model->where('device_type', '2')->where('status', 1)->order('version_id desc')->limit(1)->find();
            $filename = $pen->update_url;
            $path = config('huisheng.package_upload_path') . DS . $filename;
            if (is_file($path)) {
                download_result_one($path);
            } else {
                return resultArray(['error' => '文件不存在']);
            }
        } else {
            return resultArray(['error' => '请求被拒绝']);
        }
    }

    //下载最新版本录音笔
    public function appOfHeadVersion()
    {
        if (config('huisheng.CAN_DOWNLOAD_PEN_APP')) {
            $model = Model('Version');
            $pen = $model->where('device_type', '2')->where('status', 1)->order('version_id desc')->limit(1)->find();
            return resultArray(['data' => $pen]);
        } else {
            return resultArray(['error' => '请求被拒绝']);
        }
    }

    //web端获取title等配置
    public function getWebConfig()
    {
        $data = [
            'title' => lang('MANAGEMENT_TITLE'),
            'separate_num' => config('huisheng.SEPARATE_NUM'),
        ];
        return resultArray(['data' => $data]);
    }

    //检查sn
    public function checkSN()
    {
        $result = [
            'status' => 0,
        ];
        $sn_model = Model('UserHasSn')->get(['sn' => input('param.account')]);
        //如果sn码没有
        if (!$sn_model) {
            return resultArray(['data' => $result]);
        }
        //如果已经绑定user
        if ($sn_model->uid) {
            return resultArray(['data' => $result]);
        }
        //判断登录密码
        if (input('param.password') !== '000000') {
            return resultArray(['data' => $result]);
        }
        $result['status'] = 1;
        $result['scenes'] = Db::name('scenes')->where('status', '1')->field('id as value, name as label')->select();
        return resultArray(['data' => $result]);
    }

    public function registerSN()
    {
        try {
            $params = input('param.');
            if (!preg_match('/^[@_.A-Za-z0-9]{6,12}+$/', trim($params['username']))) {
                return resultArray(['error' => '用户名格式错误']);
            }
            if (!preg_match('/^[a-zA-Z0-9]{6,12}$/', trim($params['password']))) {
                return resultArray(['error' => '密码格式错误']);
            }
            if (!preg_match('/^1[345789]\d{9}$/', trim($params['phone']))) {
                return resultArray(['error' => '手机格式错误']);
            }
            if (Model('User')->where(['username' => trim($params['username'])])->find()) {
                return resultArray(['error' => '用户名已存在']);
            }
            Db::startTrans();

            $params['status'] = 1;
            $params['structure_id'] = 1;
            $params['user_group'] = 4;
            $params['password'] = user_md5($params['password']);
            $params['nickname'] = $params['nickname'] ?: '';
            $params['create_time'] = time();
            $params['update_time'] = time();

            $user = Model('User');
            $user->data($params)->allowField(true)->save();
            Db::table('rszh_admin_access')->insert(array('user_id' => $user->id, 'group_id' => 4));
            $sn = Model('UserHasSn')->get(['sn' => $params['sn']]);
            if (!$sn) {
                return resultArray(['error' => '录音笔sn不存在', 'code' => 405]);
            }
            if ($sn->uid) {
                return resultArray(['error' => '录音笔sn已绑定用户', 'code' => 406]);
            }
            $sn->uid = $user->id;
            $sn->first_time = time();
            $sn->update_time = time();
            $sn->save();

            //加入sn组
            if ($dep = Model('Department')->get(['title' => 'sn'])) {
                $param = [
                    'did' => $dep->dptid,
                    'uid' => $user->id,
                ];
                Model('GroupUser')->data($param)->save();
            }
            Db::commit();

            // 生成token
            $authKey = $user->makeToken();
            return resultArray(['data' => ['token' => $authKey]]);
        } catch (\Exception $e) {
            Db::rollback();
            var_dump($e->getMessage());
            return resultArray(['error' => '注册失败']);
        }
    }

    public function getIp()
    {
        $file_path = "./Ip/ip.txt";
        $result = explode("\n",file_get_contents($file_path));
        foreach($result as $key=>$row)
        {
            if(!$row)
            {
                unset($result[$key]);
            }
        }
        $returnResult['code'] = 200;
        $returnResult['data']['list'] = array_values($result);
        $returnResult['error'] = '';

        return resultArray($returnResult);
    }
}
